package com.zhiqingchun.web.comment;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sun.org.apache.bcel.internal.generic.GETSTATIC;
import com.zhiqingchun.common.exception.YouAreNotYouException;
import com.zhiqingchun.dao.comment.CommentResult;
import com.zhiqingchun.dao.comment.ICommentDao;
import com.zhiqingchun.pojo.CommentDO;
import com.zhiqingchun.pojo.Usr;

@Controller
public class CommentController {

	/**
	 * 增加评论
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/comment.html")
//	@RequestMapping(method = RequestMethod.POST)
	public String comment(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8") ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String comment = request.getParameter("comment");
		String articleId = request.getParameter("articleId");
		CommentDO commentDO = new CommentDO();
		commentDO.setArticleId(Integer.parseInt(articleId));
		commentDO.setContent(comment);
		commentDO.setTime(new Date());
		Usr usr = (Usr) request.getSession().getAttribute("user");
		commentDO.setUsrId(usr.getId());
		commentDao.add(commentDO);
		return "redirect:article.html?id=" + articleId;
	}
	
	@RequestMapping("/delComment.html")
	public String delComment(ModelMap map, HttpServletRequest request, HttpServletResponse response,
			CommentDO commentDO) {
		CommentResult commentResult = commentDao.byCommentId(commentDO);
		if (commentResult.isSuccess()) {
			Usr usr = (Usr) request.getSession().getAttribute("user");
			if (commentResult.getCommentDO().getUsrId() == usr.getId()) {
				commentDao.del(commentDO);
			} else {
				YouAreNotYouException youAreNotYouException = new YouAreNotYouException();
				youAreNotYouException.setInfo("您无权进行此项操作");
				throw  youAreNotYouException;
			}
			
		}
		return "redirect:article.html?id=" + commentDO.getArticleId();
	}
	
	@Autowired
	private ICommentDao commentDao;

	public ICommentDao getCommentDao() {
		return commentDao;
	}

	public void setCommentDao(ICommentDao commentDao) {
		this.commentDao = commentDao;
	}

}
